<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <view class="uni-sub-title">房屋管理</view>
      <view class="hor-layout-side-center" style="width: 65%">
        <view>
          <el-select v-model="queryPara.selectBuild" @change="changeSelectPara" clearable size="small"
                     placeholder="请选择楼栋号"
                     class="info-select">
            <el-option v-for="item in buildings" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-select v-model="queryPara.selectUnit" @change="changeSelectPara" clearable size="small"
                     placeholder="请选择单元号"
                     class="info-select">
            <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </view>
        <view>
          <el-button size="small" type="primary" @click="switchAddDialog(true)">新增</el-button>
          <el-button size="small" type="primary" @click="naviToAddBatch">批量导入</el-button>
        </view>
      </view>
    </view>
    <view class="uni-container">
      <el-button type="danger" size="mini" style="margin-bottom: 10px" v-show="showDeleteBtn" @click="deleteHouseBatch">
        批量删除
      </el-button>
      <el-table :data="houseList" @selection-change="handleSelectionChange" border :header-cell-style="getTableHeader">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="build_house_num" label="楼房号"></el-table-column>
        <el-table-column prop="build_num_str" label="楼栋号"></el-table-column>
        <el-table-column prop="unit_num_str" label="单元号"></el-table-column>
        <el-table-column prop="house_num" label="房号"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="create_date" label="创建日期"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="showUpdateDia(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="deleteHouseById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <view class="hor-layout-center-all" style="margin-top:15px;">
        <span class="total-view">共{{ queryPara.total }}条</span>
        <el-pagination background small layout="sizes, prev, pager, next"
                       :current-page="queryPara.current" :page-size="queryPara.size" :page-sizes="[10, 20, 30]"
                       :total="queryPara.total" @current-change="handleCurrentChange"
                       @size-change="handleSizeChange"></el-pagination>
      </view>
    </view>
    <!-- 新增弹窗   -->
    <el-dialog center :title="formData._id?'修改房号':'新增房号'" :visible="showAddDialog" @close="switchAddDialog(false)">
      <el-form label-width="100px" label-position="left" style="margin-left: 20%">
        <el-form-item label="选择楼栋号" required>
          <el-select v-model="formData.build_num" clearable size="small" placeholder="请选择楼栋号">
            <el-option v-for="item in buildings" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择单元号" required>
          <el-select v-model="formData.unit_num" clearable size="small" placeholder="请选择单元号">
            <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房号" required>
          <el-input type="number" v-model="formData.house_num" placeholder="请输入房号" size="small"
                    style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="formData.username" placeholder="请输入姓名" size="small" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input v-model="formData.phone" maxlength="11" placeholder="请输入手机号" size="small"
                    style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="switchAddDialog(false)">取 消</el-button>
        <el-button type="primary" @click="addHouse" :loading="addHouseIng">确定</el-button>
      </div>
    </el-dialog>
  </view>
</template>

<script>
import { data } from "../../../common/house";
import { getBuildHouseObj } from "@/common/common.js"

export default {
  name: "list",
  data() {
    return {
      ...data,
      queryPara: {
        selectBuild: '',
        selectUnit: '',
        total: 0,
        current: 1,
        size: 10
      },
      houseList: [],
      selHouseIds: [],
      showAddDialog: false,
      addHouseIng: false,
      formData: {
        build_num: '',
        unit_num: '',
        house_num: '',
        username: '',
        phone: ''
      }
    }
  },
  computed: {
    showDeleteBtn() {
      return this.selHouseIds.length > 0
    },
    getTableHeader() {
      return {background: '#F3F4F7', color: '#555'}
    }
  },
  onShow() {
    this.getHouseList()
  },
  methods: {
    naviToAddBatch() {
      uni.navigateTo({url: '/pages/plot/house/addBatch'})
    },
    switchAddDialog(visible) {
      this.showAddDialog = visible
      if (!visible) {
        delete this.formData._id
        for (const key in this.formData) {
          this.formData[key] = ''
        }
      }
    },
    handleSelectionChange(val) {
      this.selHouseIds = val.map(item => item._id)
    },
    addHouse() {
      this.addHouseIng = true
      if (this.formData._id) {
        this.updateHouseById()
        return
      }
      let {_id, build_num, unit_num, house_num, username, phone} = this.formData
      let params = {build_num, unit_num, house_num, username, phone}
      this.$db.collection("plot-house").add(params).then(res => {
        this.$message.success("新增成功！")
        this.getHouseList()
        this.showAddDialog = false
      }).catch(err => this.$message.error(err.message))
          .finally(() => this.addHouseIng = false)
    },
    handleCurrentChange(val) {
      this.queryPara.current = val
      this.getHouseList()
    },
    handleSizeChange(val) {
      this.queryPara.size = val
      this.getHouseList()
    },
    changeSelectPara() {
      this.queryPara.size = 10
      this.queryPara.current = 1
      this.getHouseList()
    },
    getHouseList() {
      let build_num = this.queryPara.selectBuild || this.$dbCmd.neq('')
      let unit_num = this.queryPara.selectUnit || this.$dbCmd.neq('')
      let params = {build_num, unit_num}
      let {current, size} = this.queryPara
      let skip = (current - 1) * size
      this.$db.collection("plot-house").where(params).skip(skip).limit(size)
          .orderBy("create_date", "desc").get({"getCount": true})
          .then(res => {
            let list = res.result.data
            this.queryPara.total = res.result.count
            this.houseList = list.map(item => {
              let {create_date, build_num_str, unit_num_str, build_house_num} = getBuildHouseObj(item)
              return {
                ...item,
                create_date: this.$formatDate(create_date),
                build_num_str,
                unit_num_str,
                build_house_num
              }
            })
          }).catch(err => this.$message.error(err.message))
    },
    deleteHouseBatch() {
      this.$confirm("确认删除选中项？", '确认信息').then(res => {
        this.$db.collection("plot-house").where({_id: this.$dbCmd.in(this.selHouseIds)}).remove().then(res => {
          this.$message.success("删除成功！")
          this.getHouseList()
        }).catch(err => this.$message.error(err.message))
      })
    },
    showUpdateDia(house) {
      this.formData = {...house}
      this.showAddDialog = true
    },
    updateHouseById() {
      console.log(this.formData)
      let {_id, build_num, unit_num, house_num, username, phone} = this.formData
      let params = {build_num, unit_num, house_num, username, phone}
      this.$db.collection("plot-house").doc(_id).update(params).then(res => {
        this.$message.success("更新成功！")
        this.showAddDialog = false
        this.getHouseList()
      }).catch(err => this.$message.error(err.message))
          .finally(() => this.addHouseIng = false)
    },
    deleteHouseById(house) {
      let houseNum = this.$bHouseNum(house)
      this.$confirm(`确认删除【${houseNum}】？`, '确认信息').then(res => {
        this.$db.collection("plot-house").where({_id: house._id}).remove().then(res => {
          this.$message.success("删除成功！")
          this.getHouseList()
        }).catch(err => this.$message.error(err.message))
      })
    }
  }
}
</script>

<style scoped>
.info-select {
  width: 130px;
  margin: 5px
}

.total-view {
  font-size: 13px;
  margin-top: 3px;
  margin-right: 10px;
  color: #606266;
}
</style>
